<template>
  <div class='container'>
    <!-- 精选题库 -->
    <el-card class="box-card">
      <div class="add">
        <el-button type="success" round icon="el-icon-edit" size="mini" class="addBtn" @click="addQuestion">新增试题</el-button>
      </div>
      <el-form :inline="true" :model="formInline" class="demo-form-inline" size="mini" ref="reForm" label-width="">
        <!-- 第一行 -->
        <el-row>
          <el-col :span="6">
            <el-form-item label="学科" prop="subjectID">
              <el-select v-model="formInline.subjectID" placeholder="请选择" @change="selectSub">
                <el-option :label="item.subjectName" :value="item.id" v-for="item in subjects" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="目录" prop="catalogID">
              <el-select v-model="formInline.catalogID" placeholder="请选择">
                <el-option :label="catal.directoryName" :value="catal.id" v-for="catal in catalList" :key="catal.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="标签" prop="tags">
              <el-select v-model="formInline.tags" placeholder="请选择">
                <el-option :label="tag.tagName" :value="tag.tagName" v-for="tag in tagsList" :key="tag.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="关键字" prop="keyword">
              <el-input v-model="formInline.keyword"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第二行 -->
        <el-row>
          <el-col :span="6">
            <el-form-item label="试题类型" prop="questionType">
              <el-select v-model="formInline.questionType" placeholder="请选择">
                <el-option label="单选" :value="1"></el-option>
                <el-option label="多选" :value="2"></el-option>
                <el-option label="简单" :value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="难度" prop="difficulty">
              <el-select v-model="formInline.difficulty" placeholder="请选择">
                <el-option label="简单" :value="1"></el-option>
                <el-option label="一般" :value="2"></el-option>
                <el-option label="困难" :value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="方向" prop="direction">
              <el-select v-model="formInline.direction" placeholder="请选择">
                <el-option label="o2o" value="o2o"></el-option>
                <el-option label="外包服务" value="外包服务"></el-option>
                <el-option label="企业服务" value="企业服务"></el-option>
                <el-option label="互联网金融" value="互联网金融"></el-option>
                <el-option label="企业咨询" value="企业咨询"></el-option>
                <el-option label="互联网" value="互联网"></el-option>
                <el-option label="电子商务" value="电子商务"></el-option>
                <el-option label="其他" value="其他"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="录入" prop="creatorID">
              <el-select v-model="formInline.creatorID" placeholder="请选择">
                <el-option :label="user.username" :value="user.id" v-for="user in creatorList" :key="user.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第三行 -->
        <el-row>
          <el-col :span="6">
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="formInline.remarks"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="简介" prop="shortName">
              <el-input v-model="formInline.shortName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="城市" class="city" prop="province">
              <el-select v-model="formInline.province" placeholder="请选择" style="width:50%" @change="selectShi">
                <el-option :label="shi" :value="shi" v-for="(shi, index) in provinceList" :key="index"></el-option>
              </el-select>
              <el-select v-model="formInline.city" placeholder="请选择" style="width:50%">
                <el-option :label="area" :value="area" v-for="(area, index) in cityList" :key="index"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <!-- <el-input v-model="formInline.user" placeholder="审批人"></el-input> -->
              <el-button size="mini" @click="resetForm">清除</el-button>
              <el-button size="mini" type="primary" @click="searchInfo">搜索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- tab栏切换 -->
      <el-tabs v-model="activeName" type="card" @tab-click="switchTab">
        <el-tab-pane label="全部" name="null"></el-tab-pane>
        <el-tab-pane label="待审核" name="0"></el-tab-pane>
        <el-tab-pane label="已审核" name="1"></el-tab-pane>
        <el-tab-pane label="已拒绝" name="2"></el-tab-pane>
      </el-tabs>
      <!-- 提示内容 -->
       <div class="tipContent">
          <el-alert
          :closable="false"
          :title="'总共'+total+'条数据'"
          type="info"
          show-icon>
          </el-alert>
       </div>
      <!-- 表格数据 -->
      <el-table
        :data="tableData"
        border
        style="width: 100%">
        <el-table-column
          prop="number"
          label="试题编号"
          width="150">
        </el-table-column>
        <el-table-column
          prop="subject"
          label="学科"
          width="120">
        </el-table-column>
        <el-table-column
          prop="catalog"
          label="目录"
          width="120">
        </el-table-column>
        <el-table-column
          label="题型"
          width="120">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.questionType === 1">单选</el-tag>
            <el-tag type="info" v-else-if="scope.row.questionType === 2">多选</el-tag>
            <el-tag type="success" v-else>简单</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="题干"
          width="250">
          <template slot-scope="scope">
            <div v-html="scope.row.question"></div>
          </template>
        </el-table-column>
        <el-table-column
          label="录入时间"
          width="200">
            <template slot-scope="scope">
              <span>{{scope.row.addDate | parseTimeByString}}</span>
            </template>
        </el-table-column>
        <el-table-column
          label="难度"
          width="150">
          <template slot-scope="scope">
            <el-button size="mini" type="success" v-if="scope.row.difficulty === 1">简单</el-button>
            <el-button size="mini" type="info" v-else-if="scope.row.difficulty === 2">一般</el-button>
            <el-button size="mini" type="danger" v-else>困难</el-button>
          </template>
        </el-table-column>
        <el-table-column
          prop="creator"
          label="录入人"
          width="120">
        </el-table-column>
        <el-table-column
          label="审核状态"
          width="120">
          <template slot-scope="scope">
             <el-tag v-if="scope.row.chkState === 1">通过</el-tag>
             <el-tag type="info" v-else-if="scope.row.chkState === 0">待审核</el-tag>
             <el-tag type="danger" v-else>拒绝</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="chkRemarks"
          label="审核意见"
          width="120">
        </el-table-column>
        <el-table-column
          prop="chkUser"
          label="审核人"
          width="120">
        </el-table-column>
        <el-table-column
          label="发布状态"
          width="120">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.publishState === 1">上架</el-tag>
            <!-- <el-tag type="success" v-if="tableData[scope.$index].publishState === 1">上架</el-tag> -->
            <el-tag type="info" v-else>下架</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          header-align="center"
          width="200">
          <template slot-scope="scope">
            <el-button @click="preview(scope.row)" type="text" size="small">预览</el-button>
            <el-button type="text" size="small" :disabled="scope.row.publishState===1 || scope.row.chkState === 1 " @click="auditing(scope.row)">审核</el-button>
            <el-button type="text" size="small" :disabled="scope.row.publishState===1" @click="update(scope.row)">修改</el-button>
            <el-button type="text" size="small" @click="upShow(scope.row)">{{scope.row.publishState===0?"上架":"下架"}}</el-button>
            <el-button type="text" size="small" :disabled="scope.row.publishState===1" @click="delCurrent(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[2, 3, 4, 5]"
          :page-size="pageSize"
          layout="prev, pager, next, sizes, jumper"
          :total="total">
        </el-pagination>
      </div>
      <!-- 试题审核弹层 -->
      <el-dialog
        title="题目审核"
        :visible.sync="dialogVisible"
        width="30%">
        <!-- 表单 -->
        <el-radio v-model="auditState" :label="1">通过</el-radio>
        <el-radio v-model="auditState" :label="2">拒绝</el-radio>
        <!-- 文本域 -->
        <div class="audit">
          <el-input type="textarea" v-model.trim="auditSuggest" placeholder="请输入审核意见"></el-input>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="sureSumit">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 预览弹层 -->
      <el-dialog
        title="题目预览"
        :visible.sync="previewDialog"
        width="50%">
        <QuestionPreview :curExamInfo="curExamInfo" v-if="previewDialog"></QuestionPreview>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="previewDialog = false">关闭</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
// 引入学科列表接口
import { list as courseList } from "@/api/hmmm/subjects.js";
// 获取二级目录
import { list as twoList } from "@/api/hmmm/directorys.js";
// 获取标签列表接口
import { list as tagList } from "@/api/hmmm/tags.js";
// 获取录入人信息接口
import { simple } from "@/api/base/users.js";
// 引入获取城市信息接口
import { provinces, citys } from "@/api/hmmm/citys.js";
// 获取精选题库列表 上下架  试题审核 删除试题接口
import { choice, choicePublish, choiceCheck, remove } from "@/api/hmmm/questions.js";
// 引入预览组件
import QuestionPreview from "./question-preview.vue";
export default {
  data() {
    return {
      formInline:{
        subjectID:null, //学科id
        catalogID:null, //目录
        tags:"", //标签名称
        keyword:"", //搜索关键字
        questionType:null, //试题类型
        difficulty:null, //试题难度
        direction:"", //方向
        creatorID:null, //录入人
        remarks:"", //题目备注
        shortName:"", //企业简介
        province:"", //企业所在省
        city:"", //企业所在市
      },
      subjects:[], //学科列表
      catalList:[],//目录列表
      tagsList:[], //标签列表
      creatorList:[], //录入人
      provinceList:[], //省列表
      cityList:[], //城市列表
      activeName:"null", //当前点击的tab 获取的是name的值
      //表格数据
      tableData:[
        // {
        //   number:1,
        //   subjectID:2,
        //   catalogID:3,
        //   questionType:"单选",
        //   question:"dhjsfddkf",
        //   addDate:"2020-09-11 13:26:00",
        //   difficulty:"简单",
        //   creator:"111",
        //   chkState:0,
        //   chkRemarks:"1111",
        //   chkUser:"333",
        //   publishState:1,
        // }
      ], //表格内容数据
      page:1,
      pageSize:2,
      total:null,
      dialogVisible:false, //试题审核弹出层
      auditState:1, //审核状态
      auditSuggest:"", //审核意见
      examID:null, //试题id
      previewDialog:false, //预览弹层
      curExamInfo:{}, //当前预览的试题信息
      flag:true, //开关 搜索节流
    }
  },
  components:{
    QuestionPreview
  },
  methods:{
    // 获取录入人信息
    async getCreator(){
      try{
        const res = await simple();
        console.log(res,"录入人");
        // 渲染到页面
        this.creatorList = res.data;
      }catch(err) {
        console.log(err);
        this.$message({
          message:"获取录入人失败",
          type:"warning"
        });
      }
    },
    // 获取城市信息
    getAddress(){
      // 市 渲染
      this.provinceList = provinces();
    },
    // 获取区
    selectShi(val) {
      // console.log(val,"选择的市");
      this.cityList = citys(val);
      // 每次更换市时，清空区
      this.formInline.city = "";
    },
    //选择学科触发
    async selectSub(id) {
      // 拿到选择的学科id
      // console.log(id);
      // 请求接口
      try{
        const res = await twoList({
          subjectID:id
        });
        const result = await tagList({
          subjectID:id
        });
        console.log(res,"目录");
        console.log(result,"标签");
        // 拿到目录和标签，渲染到页面
        this.catalList = res.data.items;
        this.tagsList = result.data.items;
        // 清空目录和标签
        this.formInline.catalogID = null;
        this.formInline.tags = "";
      }catch(err){
        console.log(err);
        this.$message({
          message:"获取目录失败",
          type:"warning"
        });
      }
    },
    // 表单搜索
    searchInfo() {
      let flag = this.flag;
      // 获取表单的值
      // 判断表单的值 如果全部都没选择 不调接口
      if(flag){
        this.flag = false;
        // let searchForm = this.formInline;
        // let num = 0;
        // let length = 0;
        // for(let key in searchForm) {
        //   if(!searchForm[key]){
        //     num++;
        //   }
        //   length++;
        // }
        // if(num === length){
        //   setTimeout(()=>{
        //     this.$message({
        //     message:"筛选条件不能为空",
        //     type:"warning"
        //     });
        //     this.flag = true;
        //   },1000);
        //   return;
        // }
        // 每次点击搜索 恢复默认 默认从第一页，并且默认的每页的数量，以及tab的激活项
        this.page = 1;
        this.pageSize = 2;
        this.activeName = "null";
        setTimeout(()=>{
           // 调接口
          this.getQuestion({
            ...this.formInline,
            page:this.page,
            pagesize:this.pageSize,
          });
        },1000);
       
      }
    },
    //tab栏切换
    async switchTab(){
      const curActive = JSON.parse(this.activeName);
      // 点击tab切换时，分页应该变成默认的初始状态
      this.page = 1;
      this.pageSize = 2;
      this.getQuestion({
        ...this.formInline,
        page:this.page,
        pagesize:this.pageSize,
        chkState:curActive,
      });
    },
    // 清空表单的值
    resetForm() {
      this.$refs.reForm.resetFields();
      this.formInline.city = "";
    },
    //页面一进来获取精选题库列表
    getFullQuestion(){
     try{
        this.getQuestion({
        page:this.page,
        pagesize:this.pageSize,
      });
     }catch(err) {
      console.log(err);
      this.$message({
        message:"获取题库失败",
        type:"error"
      });
     }
    },
    // 获取精选题库
    async getQuestion(obj){
      try{
        const res = await choice(obj);
        console.log(res,"精选频道列表");
        // 渲染到页面
        this.tableData = res.data.items;
        this.total = res.data.counts;
        this.flag = true;
        console.log("ceshi");
      }catch(err){
        console.log(err);
         this.$message({
          message:"获取题库失败",
          type:"warning"
        });
      }
    },
    //切换每页的数量
    handleSizeChange(size){
      // 获取切换之后的每页的值
      this.pageSize = size;
      // 始终从第一页显示
      this.page = 1;
      let curActive = JSON.parse(this.activeName);
      // 调接口
      this.getQuestion({
        ...this.formInline,
        page: this.page,
        pagesize: size,
        chkState: curActive,
      });
    },
    //切换第几页触发
    handleCurrentChange(page){
      let curActive = JSON.parse(this.activeName);
      // 获取当前切换的页码
      this.page = page;
      // 调接口
      this.getQuestion({
        ...this.formInline,
        page:this.page,
        pagesize:this.pageSize,
        chkState:curActive,
      });
    },
    // 新增题库
    addQuestion() {
      // 路由跳转到试题录入页面
      this.$router.push("/questions/new");
    },
    // 获取学科列表
    async getCourseList(){
      try{
        const res = await courseList();
        console.log(res,"学科列表");
        this.subjects = res.data.items;
      }catch(err) {
        console.log(err);
        this.$message({
          message:"学科列表获取失败",
          type:"warning"
        });
      }
    },
    // 上下架试题
    upShow(obj) {
      // 试题id
      const id = obj.id;
      // 试题发布状态
      let pubState = obj.publishState === 0 ? 1 : 0;
      if(pubState === 1){
        // 上架
        // 弹出提示框
        this.$confirm('您确认上架这道题目吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          // 确认
          this.updownQuestion(id,pubState);
          // 提示
          this.$message({
            message:"上架成功",
            type:"success"
          });
        }).catch(() => {
          //取消
          this.$message('您已取消上架');
        });
      }else {
        // 下架
        this.$confirm('您确认下架这道题目吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          // 确认
          this.updownQuestion(id,pubState);
          this.$message({
            message:"下架成功",
            type:"success"
          });
        }).catch(() => {
          //取消
          this.$message('您已取消下架');
        });
      }
      
    },
    // 上下架试题
    async updownQuestion(id,pubState){
      try{
        // 调接口
        const res = await choicePublish({
          id:id,
          publishState:pubState,
        });
        console.log(res,"上下架");
        // 修改本地数据，同步更新
        // 重新调接口
        this.getQuestion({
          ...this.formInline,
          chkState:JSON.parse(this.activeName),
          page:this.page,
          pagesize:this.pageSize,
        });
      }catch(err) {
        console.log(err);
        this.$message({
          message:"修改试题发布状态失败",
          type:"warning"
        });
      }
    },
    // 修改试题
    update(row) {
      // 携带试题的id，跳转到试题录入
      let id = row.id;
      // this.$router.push(`/questions/new?id=${id}`);
      this.$router.push({
        path:"/questions/new",
        query:{
          id:id
        }
      });
    },
    // 审核试题  打开弹层
    auditing(row){
      // 打开弹层
      this.dialogVisible = true;
      // 保存当前试题id
      this.examID = row.id;
      // console.log(this.examID,"测试");
    },
    //确定审核
    async sureSumit() {
      // 点击确认，校验审核意见，不能为空
      let auditState = this.auditState;
      let value = this.auditSuggest;
      if(!value){
        this.$message({
          message:"审核意见不能为空",
          type:"warning"
        });
        return;
      }
      // 调接口修改审核状态
      try{
        const res = await choiceCheck({
          id:this.examID,
          chkState:this.auditState,
          chkRemarks:this.auditSuggest,
        });
        console.log(res,"审核");
        // 更新视图的数据
        // 从新调接口更新视图
        let curActive = JSON.parse(this.activeName);
        this.getQuestion({
          ...this.formInline,
          chkState:curActive,
          page:this.page,
          pagesize:this.pageSize,
        });
        this.$message({
          message:"试题审核成功",
          type:"success"
        });
      }catch(err) {
        console.log(err);
        this.$message({
          message:"试题审核失败",
          type:"warning"
        });
      }
      // 关闭弹层
      this.dialogVisible = false;
    },
    // 删除当前试题
    delCurrent(row) {
      // 获取当前试题id
      let id = row.id;
      // 提示确认删除
      this.$confirm('此操作将永久删除该题目, 是否删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          // 调接口
          try{
            const res = await remove({
              id:id,
            });
            console.log(res,"删除试题测试");
            // 更新本地
            this.getQuestion({
              ...this.formInline,
              chkState:JSON.parse(this.activeName),
              page:this.page,
              pagesize:this.pageSize,
            });
            this.$message({
            type: 'success',
            message: '删除成功!'
          });
          }catch(err){
            console.log(err);
            this.$message("试题删除失败");
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });   
    },
    // 预览试题
    preview(row){
      // 打开弹层
      this.previewDialog = true;
      // console.log(row,"预览");
      // 保存在data中，传递给子组件
      this.curExamInfo = row;
    }
  },
  created() {
    // 获取学科列表
    this.getCourseList();
    // 获取录入人
    this.getCreator();
    // 获取城市信息
    this.getAddress();
    this.getFullQuestion();
  }
}
</script>

<style scoped lang="less">
.container {
  padding: 10px 0px 0 10px;
  font-size: 15px;
  .add {
    margin-bottom: 10px;
    text-align: right;
    .addBtn {
      display: inline-block;
      margin-right: 40px;
    }
  }
  /deep/.el-form-item__content {
    width: 166px;
  }
  /deep/.el-form-item__label{
    width: 68px;
  }
  .tipContent {
    margin-bottom: 10px;
  }
  .pagination {
    position: relative;
    margin-top: 20px;
    overflow: hidden;
    height: 50px;
    /deep/.el-pagination {
      position: absolute;
      left: 320px;
      top: 50%;
      transform: translateY(-50%);
      width: 120px;
      z-index: 1000;
      // float: right;
      .el-pagination__jump {
        margin-left: 0px;
      }
    }
  }
  .audit {
    margin-top: 25px;
  }
}

</style>
